package com.ruanyun.modular.admin.service.impl;

import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruanyun.base.pojo.page.LayuiPageFactory;
import com.ruanyun.base.consts.PublicCommon;
import com.ruanyun.base.pojo.page.LayuiPageInfo;
import com.ruanyun.modular.admin.entity.*;
import com.ruanyun.modular.admin.mapper.*;
import com.ruanyun.modular.admin.model.result.*;
import com.ruanyun.modular.admin.service.VocManagementLedgerService;
import com.ruanyun.modular.admin.service.VocReducingPlanService;
import com.ruanyun.sys.core.shiro.ShiroKit;
import com.ruanyun.modular.admin.model.params.TProposedMeasuresPlanParam;
import  com.ruanyun.modular.admin.service.TProposedMeasuresPlanService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanyun.sys.modular.system.entity.User;
import com.ruanyun.sys.modular.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.tio.utils.jfinal.P;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 拟实施措施计划 服务实现类
 * </p>
 *
 * @author zs
 * @since 2021-04-19
 */
@Service
public class TProposedMeasuresPlanServiceImpl extends ServiceImpl<TProposedMeasuresPlanMapper, TProposedMeasuresPlan> implements TProposedMeasuresPlanService {

    @Autowired
    private TCommitReportMapper commitReportMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private VocReducingPlanService vocReducingPlanService;
    @Autowired
    private VocManagementLedgerService ledgerService;



    @Override
    public ResponseData add(TProposedMeasuresPlanParam param){
        TProposedMeasuresPlan entity = getEntity(param);
        entity.setDelFlag(PublicCommon.DEL_FLAG_NORMAL);
        if(entity.getCompanyId() ==null ){
            return  ResponseData.error("未选择企业所属企业 清先查看企业信息是否填写完整");
        }
        Integer count = commitReportMapper.getIsCommit(userService.getCid());
        if(count > 0 ){
            return  ResponseData.error("该条信息已提交报告无法继续添加");
        }

        try {
            this.baseMapper.insert(entity);
        } catch (DuplicateKeyException e){
            return ResponseData.error("请选择其他企业");
        }
        return ResponseData.success();
    }

    @Override
    public void delete(TProposedMeasuresPlanParam param){
        this.removeById(getKey(param));
    }

    /**
    * 删除
    *
    * @param id
    * @return
    */
    @Override
    public ResponseData updateDelFlagById(Long id) {
        TProposedMeasuresPlan entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该拟实施措施计划不存在");
        }
        entity.setDelFlag(PublicCommon.DEL_FLAG_DELETE);
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("删除失败");
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData update(TProposedMeasuresPlanParam param){
        TProposedMeasuresPlan oldEntity = getOldEntity(param);
        TProposedMeasuresPlan newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        Integer count = commitReportMapper.getIsCommit(oldEntity.getCompanyId());
        if(count > 0 ){
            return  ResponseData.error("该条信息已提交报告无法修改");
        }
        int result = this.baseMapper.updateById(newEntity);
        if(result == 0){
        return ResponseData.error("修改失败失败");
        }
        return ResponseData.success();
    }

    @Override
    public TProposedMeasuresPlanResult findBySpec(TProposedMeasuresPlanParam param){
        return null;
    }

    @Override
    public List<TProposedMeasuresPlanResult> findListBySpec(TProposedMeasuresPlanParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(TProposedMeasuresPlanParam param){
        /*判断当前用户是否为管理员*/
        boolean flag = ShiroKit.isAdmin();
        Page pageContext = getPageContext();
        User u = userService.getUserInfo();
        if ("1162247971007717377".equals(u.getRoleId())){
            param.setCompanyId(userService.getCid());
            IPage page = this.baseMapper.customPageList2(pageContext, param);
            List<TProposedMeasuresPlanResult> list = page.getRecords();
            if(list.size() != 0){
                TProposedMeasuresPlanResult result = list.get(0);

                //获取措施类型
                String types = result.getPlanType();
                if(types.length()   ==  6 ){
                    result.setPlanType("源头替代,过程控制，末端处理");
                } else if(types.length() == 4){
                    if(types .equals("1,2,") ){
                        result.setPlanType("源头替代,过程控制");
                    }
                    if(types.equals("2,3,") ){
                        result.setPlanType("过程控制，末端处理");
                    }
                    if(types.equals("1,3,") ){
                        result.setPlanType("源头替代，末端处理");
                    }
                } else  if(types.length() == 2){
                    if(types.equals("1,")){
                        result.setPlanType("源头替代");
                    }
                    if(types.equals("2,")){
                        result.setPlanType("过程控制");
                    }
                    if(types.equals("3,")){
                        result.setPlanType("末端处理");
                    }
                }

                   String  leds = list.get(0).getLedgerIds().replaceAll(",","");
                   Integer total = leds.length();
                    result.setLedgerCount(total);
                    list.set(0,result);
                page.setRecords(list);

            }
           return    LayuiPageFactory.createPageInfo(page);

        } else  {
            if("1402427539539161089".equals(u.getRoleId())){//市管理账号
                param.setIsArea("y");
            }

            if("1402427690353750018".equals(u.getRoleId()) ){ //县管理账号
                param.setCountyId(String.valueOf(u.getUserId()));
            }
            IPage page = this.baseMapper.customPageList2(pageContext, param);
            List<TProposedMeasuresPlanResult> list = page.getRecords();
             if(list.size()!= 0){
                 for (TProposedMeasuresPlanResult result : list) {
                     //获取措施类型
                     String types = result.getPlanType();
               List<VocManagementLedgerResult> ledgerLists  =      ledgerService.getLedgerLists(result.getCompanyId());
                 if(ledgerLists.size() != 0){
                     result.setLedgerCount(ledgerLists.size());
                 } else {
                     result.setLedgerCount(0);
                 }
                     if(types.length()   ==  6 ){
                         result.setPlanType("源头替代,过程控制，末端处理");
                     } else if(types.length() == 4){
                         if(types .equals("1,2,") ){
                             result.setPlanType("源头替代,过程控制");
                         }
                         if(types.equals("2,3,") ){
                             result.setPlanType("过程控制，末端处理");
                         }
                         if(types.equals("1,3,") ){
                             result.setPlanType("源头替代，末端处理");
                         }
                     } else  if(types.length() == 2){
                         if(types.equals("1,")){
                             result.setPlanType("源头替代");
                         }
                         if(types.equals("2,")){
                             result.setPlanType("过程控制");
                         }
                         if(types.equals("3,")){
                             result.setPlanType("末端处理");
                         }
                     }

                 }
             }


                page.setRecords(list);
          return   LayuiPageFactory.createPageInfo(page);

        }




    }

    private Serializable getKey(TProposedMeasuresPlanParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private TProposedMeasuresPlan getOldEntity(TProposedMeasuresPlanParam param) {
        return this.getById(getKey(param));
    }

    private TProposedMeasuresPlan getEntity(TProposedMeasuresPlanParam param) {
        TProposedMeasuresPlan entity = new TProposedMeasuresPlan();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }
    /**
        * 启用
        *
        * @param id
        * @return
        */
    @Override
    public ResponseData enableById(Long id) {
        TProposedMeasuresPlan entity = this.baseMapper.selectById(id);
        if (entity == null) {
        return ResponseData.error("该拟实施措施计划不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("启用失败");
        }
        return ResponseData.success();
    }

    /**
     * 禁用
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData disableById(Long id) {
        TProposedMeasuresPlan entity = this.baseMapper.selectById(id);
        if (entity == null) {
            return ResponseData.error("该拟实施措施计划不存在");
        }
        int result = this.baseMapper.updateById(entity);
        if (result == 0) {
            return ResponseData.error("禁用失败");
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData commitReport(Long companyId) {
//          Integer count = reportMapper.getDetails(companyId);
//           if(count >0){
//               return  ResponseData.error("该条信息已提交,请勿再次提交");
//           }
//         TCommitReport tCommitReport = new TCommitReport();
//         tCommitReport.setCompanyId(Math.toIntExact(companyId));
//         //根据 企业id 查询 信息是否填充完整
//        TBasicMaterial tBasicMaterial = tBasicMaterialMapper.getDetails(companyId);
//         if(tBasicMaterial != null) {
//            tCommitReport.setMaterId(tBasicMaterial.getId());
//         }else {
//              return  ResponseData.error("材料信息未填写完整");
//         }
//
//         TExhaustEquipment tExhaustEquipment = tExhaustEquipmentMapper.getDetails(companyId);
//          if(tExhaustEquipment != null){
//              tCommitReport.setEquipmentId(tExhaustEquipment.getId());
//          } else {
//              return ResponseData.error("废气治理设施未填写完整");
//          }
//
//          TExhaustOutlet tExhaustOutlet = tExhaustOutletMapper.getDetails(companyId);
//           if(tExhaustOutlet != null){
//               tCommitReport.setExhaustId(tExhaustOutlet.getId());
//           }else {
//               return  ResponseData.error("废气排放口信息未填写完整");
//           }
//
//           TMonitoringinfo tMonitoringinfo = tMonitoringinfoMapper.getDetails(companyId);
//            if(tMonitoringinfo != null){
//                tCommitReport.setMonitoringId(tMonitoringinfo.getId());
//            }else {
//                return  ResponseData.error("监测信息未填写完整");
//            }
//
//            TProductEquipment tProductEquipment = tProductEquipmentMapper.getDetails(companyId);
//             if(tProductEquipment != null){
//                 tCommitReport.setPequipmentId(tProductEquipment.getId());
//             }else {
//                 return  ResponseData.error("生产设备信息未填写完整");
//             }
//
//             TProductinfo tProductinfo = tProductinfoMapper.getDetails(companyId);
//              if(tProductinfo != null){
//                  tCommitReport.setProductId(tProductinfo.getId());
//              } else {
//                  return  ResponseData.error("产品信息未填写完整");
//              }
//
//              TProductionProcess tProductionProcess = tProductionProcessMapper.getDetails(companyId);
//              if(tProductionProcess != null){
//                   tCommitReport.setPpId(tProductionProcess.getId());
//              }else {
//                  return  ResponseData.error("生产工艺信息未填写完整");
//              }
//
//              VocManagementLedger vocManagementLedger = vocManagementLedgerMapper.getDetails(companyId);
//               if(vocManagementLedger != null){
//                    tCommitReport.setLedgerId(vocManagementLedger.getId());
//               } else  {
//                   return  ResponseData.error("台账信息未填写完整");
//               }
//
//               TProposedMeasuresPlan tProposedMeasuresPlan = this.baseMapper.getDetails(companyId);
//                tCommitReport.setPlanId(tProposedMeasuresPlan.getId());
//                  tCommitReport.setCreateTime(new Date());
//                  tCommitReport.setDelFlag(1);
//                int result =reportMapper.insert(tCommitReport);
//                if(result >0 ){
//                    return  ResponseData.success("提交成功");
//                }else {
//                    return  ResponseData.error("提交失败");
//                }

    return  ResponseData.success();

    }

    @Override
    public TProposedMeasuresPlanResults getDetail(Integer id) {

        return baseMapper.getDetail(id);
    }






    @Override
    public Page<TMeasuresResult> getProposedMeasuresPlanPage(Integer companyId) {
        Page pageContext = getPageContext();

             Integer rid = vocReducingPlanService.getIdByCid(companyId);
             Page<TMeasuresResult>  resultPage =   baseMapper.getVocsPage(pageContext,rid);
             return resultPage;

    }

    @Override
    public Page<VocManagementLedgerResult> getLedgerPage(Integer companyId) {

        Page pageContext = getPageContext();
        Page<VocManagementLedgerResult>  resultPage =   baseMapper.getLedgerPage(pageContext,companyId);
        return resultPage;

    }


}
